//
//  TaskTestView.swift
//  MakeMoney
//
//  Created by Fan ZhiQiang on 2025/8/19.
//

import SwiftUI
/**
 * 这里的Task任务是开启了一个异步新线程，在新线程里运行耗时操作，并不会影响主线程的UI刷新。
 * 这里的代码运行是串行的，自上而下，await方法会卡住异步任务，任务结束后再往下运行
 */
struct TaskTestView: View {
    @State private var isShow = false
    @State private var isUploading = false
    @State private var isOn = false
    var body: some View {
        Button("上传") {
            Task {
                isUploading = true
                print("now is uploading")
                await uploadMonitor()
                print("now is async")
                let newString = await getNewString()
                print(newString)
                isUploading = false
            }
        }
        Text(isUploading ? "Uploading..." : "UploadSuccess")
        Toggle("开关", isOn: $isOn)
        
        Button("模态弹出") {
            
        }
        
    }
    
    func uploadMonitor() async {
        print("uploadMonitor")
        try? await Task.sleep(for: .seconds(5))
        print("sleep over")
    }
    
    func getNewString() async -> String {
        print("getNewString")
        try? await Task.sleep(for: .seconds(3))
        print("sleep over")
        return "这里给你一个新字符串"
    }
}

#Preview {
    TaskTestView()
}

//让一个类线程安全
final class TasktestClass: @unchecked Sendable {
    let lock = DispatchQueue(label: "com.myapp.task")
    
    private var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func updateName(name: String) {
        lock.async {
            self.name = name
        }
    }
}
